<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共19条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="downloadExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList" :default-sort="{prop: 'workNumber'}">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formatter" />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column label="入职时间" sortable>
            <template slot-scope="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="转正时间" sortable>
            <template slot-scope="scope">
              <span>{{ scope.row.correctionTime | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="assigningroles(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmploy(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <!-- 新增员工弹框组件 -->
        <el-dialog v-if="showDialog" title="新增员工" :visible.sync="showDialog">
          <emp-dialog @close="showDialog=false" />
        </el-dialog>

        <!-- 分配角色弹窗 -->
        <el-dialog title="分配角色" :visible="showRoleDialog" @close="showRoleDialog=false">
          <assign-role v-if="showRoleDialog" :user-roleid="userRoleid" @closero="showRoleDialog=false" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入时间插件
import dayjs from 'dayjs'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDialog from './empDialog'
// 引入分配角色插件
import assignRole from './assignRole.vue'

export default {
  name: 'Employees',
  components: {
    EmpDialog,
    assignRole
  },
  filters: {
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false,
      showRoleDialog: false, // 分配角色的弹框
      userRoleid: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 分配角色按钮
    assigningroles(id) {
      this.showRoleDialog = true
      this.userRoleid = id
    },

    // 处理导出函数的方法
    transData(rows) {
      // 2 - 用一个枚举 ,方便转化
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const headerKeys = Object.keys(rows[0])
      const Header = headerKeys.map(item => {
        return map[item]
      })
      const data = rows.map(item => {
        return Object.values(item)
      })
      return { Header, data }
    },
    // 导出excel
    async downloadExcel() {
    //   获取需要导出的数据
      const res = await getEmployeeList(this.query)
      const excelObj = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: excelObj.Header, // 导出的文件的表头
          data: excelObj.data, // 导出的文件的内容
          filename: '员工列表', // 导出的文件名称
          autoWidth: true, // 宽度自适应
          bookType: 'xlsx' // 文件格式
        })
      })
    },
    // 删除员工
    delEmploy(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async err => {
        if (err === 'confirm') {
          const res = await delEmployee(id)
          this.$message.success(res.message)
          if (this.employeesList.length === 1) {
            this.query.page--
            if (this.query.page <= 0) {
              this.query.page = 1
            }
          }
          this.getEmployeeList()
        }
      }).catch(err => {
        if (err === 'cancel') {
          this.$message('已经取消删除')
        }
      })
    },
    // 利用这个方法格式化用工形式
    formatter(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async getEmployeeList() {
      const res = await getEmployeeList(this.query)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped></style>
